<?php


namespace app\api\controller\v1;


use app\admin\model\BdOrg;
use app\admin\model\Wxuser;
use app\common\controller\JwtTools;
use think\Cache;
use think\Config;
use think\Env;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use think\Session;
use think\Validate;

class Base
{
    protected $params;
    /**
     * @var Request Request 实例
     */
    protected $request;
    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';
    /**
     * 用户id
     * @var string
     */
    protected $user_id = '';
    protected $user_info = '';
    protected $token = '';
    //默认未登录或未审核 取默认组织和数据中心
    protected $forgid       = 27111111;
    protected $datacenter   = 1842944793479483392;
    protected $forgids;
    protected $customer_id      = '';
    protected $bizperson_id     = '';

    protected $pageSize = 6;

    protected $cacheExpire = 604800;

    /**
     * 未登录状态码
     * @var string
     */
    protected $loginErorCode = 302;
    /**
     * 未登录状态码
     * @var string
     */
    protected $loginErorCodeGuoqi = 303;
    /**
     * 不需要登录的控制器方法
     * @var array
     */
    protected $dontNeedTokenApi = [
        '/api/v1/login/login',
        '/api/v1/login/getService',
        '/api/v1/index/index',
        '/api/v1/index/index',
        '/api/v1/index/material',
        '/api/v1/index/getNotice',
        '/api/v1/index/noticeDetail',
        '/api/v1/login/codeChangeMessage',
        '/api/v1/login/sendCms',

        '/api/v1/Basic/getMaterialcate',
        '/api/v1/Basic/getMatpop',
        '/api/v1/Basic/getSurface',
        '/api/v1/Basic/getTexture',

        '/api/v1/Spot/tabulation',
        '/api/v1/Spot/detail',

        '/api/v1/login/sendCms',
        '/api/v1/login/sendCms',
        '/api/v1/login/sendCms',
        '/api/v1/login/sendCms',
        '/api/v1/login/sendCms',

    ];

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = $request ?? Request::instance();

        // 控制器初始化
        $this->init();

        $this->params = $this->request->param();
    }

    protected function init()
    {
        $this->checkMethod();

        //跨域请求检测
        check_cors_request();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $header = $this->request->header();
        $this->request->user_id = null; // 初始化user_id属性为null

        if (!empty($header['token'])) {

            $jwt = new JwtTools();
            $res = $jwt->de_token($header['token']);

            if ($res['code'] == 'success' && isset($res['data']['data']))
            {
                $this->token = $header['token'];
                $userData = $res['data']['data'];
                if (is_object($userData) && property_exists($userData, 'user_id')) {
                    $this->request->user_id = $userData->user_id;
                } elseif (is_array($userData) && array_key_exists('user_id', $userData)) {
                    $this->request->user_id = $userData['user_id'];
                }
            } else {
                $this->error($res['data'],'',$res['code']);
            }
        }





        $this->checkLogin();
        $this->setDefalt();

        $this->userInfo();
    }


    /**
     * 操作成功返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为1
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型，支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 验证是否需要登录
     * @access protected
     * @return bool
     */
    public function checkLogin()
    {



        if (in_array(request()->url(), $this->dontNeedTokenApi)) {
            return true;
        }else{
            if (empty($this->request->user_id)) {
                return $this->result('请先登录',[], $this->loginErorCode);
            }

            $session = Wxuser::get($this->request->user_id)['fk_bdl_token'];
            if($session != $this->token)
            {
                return $this->result('登录状态已过期，请重新登录',[], $this->loginErorCodeGuoqi);
            }
        }





        return true;
    }



    /**
     * 验证方法
     * @param $param 对比的参数
     * @param $field 需要过滤的字段
     * @param $notes 注释的信息
     * @return array
     */
    public function plulicValidate($params, $field, $notes)
    {
        $data = [];

        foreach ($field as $k => $v) {
            $data[$v] = $notes[$k];
        }

        $validate = Validate::make($data);

        if (!$validate->check($params)) {
            return ['code' => 1, 'msg' => $validate->getError()];
        } else {
            return ['code' => 0];
        }
    }

    public function checkMethod()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST')
        {
            return true;
        } else {
            return $this->result('请求错误',[],405);
        }
    }

    //获取库存状态信息
    public function getInventoryStatusMessage($count) {
        if (!$count) {
            return '暂无库存';
        } elseif ($count <= 1) {
            return '库存紧张';
        } else {
            return '库存充足';
        }
    }

    public function buildTree(array $items, $parentId = '') {
        $tree = [];
        foreach ($items as $item) {
            if ($item['fk_bdl_super'] == $parentId) {
                $node = $this->buildTree($items, $item['id']);
                if ($node) {
                    $item['children'] = $node;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }

    public function userInfo()
    {
        $cacheTag       = \config('cache_tag')['v1_base_user'];

        if($this->request->user_id)
        {
            $cacheKey       = $cacheTag. $this->request->user_id;
            $userData       =  Cache::get($cacheKey);

            if(!$userData)
            {
                $userData = Wxuser::with('customer')->find($this->request->user_id);

//                if($userData['fenable'] == 0)
//                {
//                    $this->result('用户已被禁用',[],504);
//                }
//

                Cache::tag($cacheTag)->set($cacheKey,$userData,$this->cacheExpire);
            }

            if(!empty($userData['forgid']))
            {
                $this->datacenter       = !empty($userData['fk_bdl_bd_datacenter']) ? $userData['fk_bdl_bd_datacenter'] : $this->datacenter;
            }

            $this->customer_id      = $userData['fk_bdl_bd_customer'];
            $this->bizperson_id     = $userData['fk_bdl_bd_bizperson'];
            $this->user_id          = $this->request->user_id;
            $this->user_info        = $userData;
        }


        $this->forgid           = !empty($userData['forgid']) ? $userData['forgid'] : $this->forgid;
        $forg                   = BdOrg::get($this->forgid);
        $fnumbers               = explode(",",$forg['fk_bdl_mappingorg']);

        if(empty($fnumbers[0]))
        {
            $this->forgids = [$this->forgid];

        }else{
            $this->forgids           = BdOrg::whereIn('fnumber',$fnumbers)->where('fk_bdl_bd_datacenter',$this->datacenter)->column('id');
        }
    }

    public function getStartEnd($type)
    {
        switch ($type)
        {
            //本月
            case 1:
                $start_time = date('Y-m-01', strtotime(date('Y-m') . '-01')) . ' 00:00:00';
                $end_time   = date('Y-m-t', strtotime(date('Y-m'))) . ' 23:59:59';
                break;
            //近30天
            case 3:
                $currentTimestamp = time();
                $thirtyDaysAgoTimestamp = $currentTimestamp - (29 * 24 * 60 * 60);
                $start_time = date('Y-m-d 00:00:00', $thirtyDaysAgoTimestamp);
                $end_time = date('Y-m-d 23:59:59', $currentTimestamp);
                break;
            //本周
            case 2:
                $now = time();
                $dayOfWeek = date('w', $now);
                $startDateOfWeek = strtotime('-' . ($dayOfWeek == 0 ? 7 : $dayOfWeek - 1) . ' days', $now);
                $endDateOfWeek = strtotime('+' . (7 - $dayOfWeek) . ' days', $now);
                $start_time = date('Y-m-d', $startDateOfWeek) . ' 00:00:00';
                $end_time = date('Y-m-d', $endDateOfWeek) . ' 23:59:59';
                break;
            //近7天
            case 4:
                $now = time();
                $today = date('Y-m-d', $now);
                $sevenDaysAgo = date('Y-m-d', strtotime('-6 days', $now));
                $end_time = $today . ' 23:59:59';
                $start_time = $sevenDaysAgo . ' 00:00:00';
                break;
        }

        return [
            'start' => $start_time,
            'end'   => $end_time
        ];
    }

    public function setDefalt()
    {
        if(Env::get('wxmini.debug'))
        {
            $this->forgid = Env::get('wxmini.debug_forgid');
            $this->datacenter = Env::get('wxmini.debug_datacenter');
        }else{
            $this->forgid = Env::get('wxmini.true_forgid');
            $this->datacenter = Env::get('wxmini.true_datacenter');
        }
    }

    //获取默认图片
    public function getDefaultImage()
    {
        $data = \app\common\model\Config::where('name','noImage')->value('value');

        return $data;
    }
}